// pages/telService/index.js
var http = require('../../../utils/http');
var api = require('../../../utils/api');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        count:0,
        disabledBtn: false,
        showOverPopup: false,
        calendarConfig: {
            defaultDay: false
        },
        showPopup: false,
        searchVal: "",
        childInfo: {},
        child_id: "",
        child: [],
        user_id: "",
        showSelectPopup: false,
        radioId: "",
        hosTea: [],
        showPopup: false,
        dateArr: [],
        current: -1,
        showCalendar: false,
        currentYear: "",
        currentMonth: "",
        currentDay: "",
        enableDays: [],
        timer: "",
        doc_name: "",
        hosname: ""
    },
    openPopupFun() {

        this.doSometing()
    },
    selectChildFun2(){
        this.setData({
            showSelectPopup: false
        })
        setTimeout(() => {
            this.init()
        }, 500);
    },
    doSometing() {
        this.calendar.enableDays(this.data.enableDays);
        if (this.data.current == -1) {
            setTimeout(() => {
                this.calendar.cancelSelectedDates();
            }, 100);
        }
        if (this.data.currentYear) {
            this.calendar.jump(this.data.currentYear, this.data.currentMonth, this.data.currentDay).then(date => {}); // 跳转至某日
        }
    },
    afterTapDay(e) {
        console.log('afterTapDay', e.detail)
        this.setData({
            currentYear: e.detail.year,
            currentMonth: e.detail.month,
            currentDay: e.detail.day,
        })
        this.data.dateArr.forEach((ele, index) => {
            if (ele.date2 == e.detail.month + '.' + e.detail.day) {
                this.setData({
                    current: index
                })
            }
        })
        let date = e.detail.year + '-' + e.detail.month + '-' + e.detail.day
        this.getTeaList(date)
        this.setData({
            showCalendar: false
        })
    },
    showCalendarFun() {
        this.setData({
            showCalendar: true
        })
    },
    onCloseCalendar() {
        this.setData({
            showCalendar: false
        })
    },
    /** 获取专家列表 */
    getDocListFun() {
        http.postHttp(api.getPublicHosDoc, {
                hos_id: this.data.id
            },
            (result) => {
                if (result.code == 0) {
                    this.setData({
                        hosTea: result.data.doc,
                        enableDays: result.data.work_time
                    })
                    let arr = this.getEveryDay()
                    this.data.enableDays.forEach(ele => {
                        arr.forEach((item, index) => {
                            if (ele == item.date) {
                                item.status = true
                            }
                        })
                    })
                    console.log(arr);
                    this.setData({
                        dateArr: arr
                    })
                }
            },
            (err) => {
                console.log(err);
            },
        )
    },
    /** 获取教师列表 */
    getTeaList(date) {
        http.postHttp(api.getPublicHosDoc, {
                hos_id: this.data.id,
                work_time: date
            },
            (result) => {
                if (result.code == 0) {
                    this.setData({
                        hosTea: result.data.doc,
                    })
                }
            },
            (err) => {
                console.log(err);
            },
        )
    },
    init() {
        const child = wx.getStorageSync('child')
        const childInfo = wx.getStorageSync('childInfo')
        const userInfo = wx.getStorageSync('userInfo')
        this.setData({
            child_id: childInfo.id ? childInfo.id : 0,
            childInfo: childInfo,
            child: child,
            user_id: userInfo.id,
            radioId: childInfo.id
        })
        this.getDocListFun()
    },
    onCloseSelectPopup() {
        this.setData({
            showSelectPopup: false
        })
    },
    /** 切换孩子 */
    changeChildFun() {
        this.setData({
            showSelectPopup: true
        })
    },
    /** 选择孩子触发 */
    onChangeRadio(e) {
        this.setData({
            radioId: e.detail.detail,
        });
    },
    selectChildFun() {
        this.data.child.forEach(ele => {
            if (this.data.radioId == ele.id) {
                wx.setStorageSync('childInfo', ele)
                if (!ele.if_vip) {
                    this.setData({
                        showSelectPopup: false
                    })
                    wx.showModal({
                        confirmText: '我知道了',
                        content: '您还不是尊享会员，无法预约，将返回到首页',
                        showCancel: false,
                        title: '温馨提示',
                        success: (result) => {
                            wx.switchTab({
                                url: '/pages/index/index',
                            })
                        },
                        fail: (res) => {},
                        complete: (res) => {},
                    })
                    return
                }
                this.init()
                this.setData({
                    showSelectPopup: false
                })
            }
        })
    },
    /** 新建预约 */
    postResrve(item) {
        http.postHttp(api.postResrve, {
                "data": {
                    "child_id": this.data.child_id,
                    "user_id": this.data.user_id,
                    "reserver_time": item.schedules[0].work_time,
                    "public_schedule_id": item.schedules[0].id
                },
                "type": "3"
            },
            (result) => {
                if (result.code == 0) {
                    this.setData({
                        timer: item.schedules[0].work_time,
                        doc_name: item.doc_name,
                        showPopup: true,
                        count:0
                    })
                }
            },
            (err) => {
                console.log(err);
            },
        )
    },
    /** 预约 */
    handleYuyue(e) {
        let item = e.currentTarget.dataset.item
        if (this.data.current == -1) {
            wx.navigateTo({
                url: '/packageA/pages/doctorDetail/index?docid=' + item.id + '&info=' + JSON.stringify(item),
            })
        } else {
            // this.setData({
            //     showPopup: true
            // })
            if (this.data.count == 0) {
                this.setData({
                    count:1
                })
                /** 先检测是否可以预约 */
                http.postHttp(api.isIfBook, {
                        rtype: "3",
                        personal_id: this.data.childInfo.personal_id
                    },
                    (result) => {
                        if (result.code == 0) {
                            if (result.data.ifok) {
                                this.postResrve(item)
                            } else {
                                console.log("不能预约");
                                this.setData({
                                    showOverPopup: true,
                                    count:0
                                })
                            }
                        }
                    },
                    (err) => {
                        console.log(err);
                    },
                )
            }

        }
    },
    handJin(e) {
        let item = e.currentTarget.dataset.item
        wx.navigateTo({
            url: '/packageA/pages/doctorDetail/index?docid=' + item.id + '&info=' + JSON.stringify(item),
        })
    },
    onClosePopup() {
        this.setData({
            showPopup: false,
            showOverPopup: false,
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let id = options.id
        this.setData({
            id: id,
            hosname: options.hosname
        })
        this.init()
        let arr = this.getEveryDay()
        this.setData({
            dateArr: arr
        })
        // console.log(arr);
    },
    selectDate(e) {
        let date = e.currentTarget.dataset.date
        let status = e.currentTarget.dataset.status
        let index = e.currentTarget.dataset.index
        let arr;
        if (status) {
            this.setData({
                current: index
            })
            arr = date == 'all' ? [] : date.split('-')
            if (arr && arr.length == 0) {
                this.calendar.cancelSelectedDates();
            }
            this.setData({
                currentYear: arr[0],
                currentMonth: arr[1],
                currentDay: arr[2],
            })
            this.getTeaList(date)
        }
        if (date == 'all') {
            this.setData({
                current: index
            })
            this.getDocListFun()
        }
    },
    getEveryDay() {
        function getCountDays() {
            var curDate = new Date();
            var curMonth = curDate.getMonth();
            curDate.setMonth(curMonth + 1);
            console.log(curDate)
            curDate.setDate(0);
            console.log(curDate)
            return curDate.getDate();
        }
        // 下个月的日期
        function getCountDays1() {
            var curDate = new Date();
            var curMonth = curDate.getMonth();
            curDate.setMonth(curMonth + 2);
            curDate.setDate(0);
            return curDate.getDate();
        }

        function getWeekArr(m) {
            var stamp = new Date().getTime()
            var day = ''
            var arr = []
            for (let i = 0; i <= m - 1; i++) {
                let day = new Date(stamp + 24 * 3600000 * i)
                // console.log(day.getDay())
                let week = getWeek(day.getDay())
                arr.push(week)
            }
            return arr
        }

        function getWeek(e) {
            var nowWeek = ''
            var weekday = []
            weekday[0] = "周日";
            weekday[1] = "周一";
            weekday[2] = "周二";
            weekday[3] = "周三";
            weekday[4] = "周四";
            weekday[5] = "周五";
            weekday[6] = "周六";
            return weekday[e]
        }
        var curDate = new Date();
        var nowDate = new Date().getDate()
        var n = curDate.getMonth();
        var y = curDate.getFullYear();
        var m = n
        n = n + 1;
        m = n + 1;

        var dayArry = [];
        var dayArry2 = [];
        var day = getCountDays();
        let weekArr = getWeekArr(day)
        for (var k = 1; k <= day; k++) {
            if (k >= nowDate) {

                dayArry.push(`${y}-${n}-${k}`);
                dayArry2.push(`${n}.${k}`);
            }
        }
        var day2 = getCountDays1();
        for (var i = 1; i <= day2; i++) {
            if (dayArry.length <= 30) {

                dayArry.push(`${y}-${m}-${i}`);
                dayArry2.push(`${m}.${i}`);
            }
        }
        let arr = []
        for (let i = 0; i <= day - 1; i++) {
            arr.push({
                date: dayArry[i],
                date2: dayArry2[i],
                text: weekArr[i]
            })
        }
        // for (let i = 0; i < arr.length; i++) {
        //     arr[0].text = '今天'
        //     arr[1].text = '明天'
        //     arr[2].text = '后天'
        // }
        return arr;
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})